import { EventSourcePolyfill } from 'event-source-polyfill';
export default {
  data() {
    return {
      IsSupportSse: 'EventSource' in window,
      stockData: null,
    };
  },
  created() {},
  mounted() {
    const view = document.getElementById('renderjs-view');
    console.log('this.source', this.source);
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.type === 'childList') {
          // 检查目标节点是否已被移除
          if (!document.contains(view)) {
            observer.disconnect(); // 停止观察
            this.source.close(); // 关闭资源
          }
        }
      });
    });

    // 开始观察文档变化
    observer.observe(document.documentElement, {
      childList: true,
      subtree: true,
    });
    //页面刷新或关闭时调用
    window.addEventListener('beforeunload', () => {
      this.source.close();
    });
  },
  methods: {
    onChange(newValue, oldValue, ownerInstance, instance) {
      console.warn('改变属性');
      if (this.source) {
        this.source.close();
      }
      if (newValue != 'null') {
        this.symbol = newValue;
        this.creartEventSource();
      }
    },
    // 发送数据到service层
    emitData() {
      UniViewJSBridge.publishHandler('onWxsInvokeCallMethod', {
        cid: this._$id,
        method: 'acceptDataFromRenderjs',
        args: {
          data: this.stockData,
        },
      });
    },
    diffUpStockData(data) {
      if (!this.stockData) {
        this.stockData = data;
      } else {
        for (let key in data) {
          this.stockData[key] = data[key];
        }
      }
    },
    random(min, max) {
      return Math.floor(Math.random() * (max - min)) + min;
    },
    creartEventSource() {
      // 检查浏览器是否支持SSE
      let that = this;
      if ('EventSource' in window) {
        let aryData = this.symbol.split('.');
        var market = 0; //市场代码
        if (aryData[1].toLowerCase() == 'sh') {
          market = 1;
        } else if (
          aryData[1].toLowerCase() == 'sz' ||
          aryData[1].toLowerCase() == 'bj'
        ) {
          market = 0;
        }
        let internalSymbol = aryData[0];
        // 将股票代码转
        let url = `https://${this.random(
          20,
          90
        )}.push2.eastmoney.com/api/qt/stock/sse`; //随机行情服务器，
        let query = `?fields=f58,f57,f43,f59,f169,f170,f152,f177,f111,f46,f60,f44,f45,f47,f137,f138,f139,f140,f141,f142,f143,f144,f145,f146,f147,f148,f149,f260,f48,f261,f279,f277,f278,f288,f19,f17,f531,f15,f13,f11,f20,f18,f16,f14,f12,f39,f37,f35,f33,f31,f40,f38,f36,f34,f32,f211,f212,f213,f214,f215,f210,f209,f208,f207,f206,f161,f49,f171,f50,f86,f84,f85,f168,f108,f116,f167,f164,f162,f163,f92,f71,f117,f51,f52,f191,f192,f262&mpi=1000&invt=2&fltt=1&secid=${market}.${internalSymbol}&ut=fa5fd1943c7b386f172d6893dbfba10b&wbp2u=|0|0|0|web`;
        this.source = new EventSourcePolyfill(url + query);

        this.source.onmessage = (event) => {
          let res = JSON.parse(event.data);
          this.diffUpStockData(res.data);
          console.log('rep', res.data);
          this.$ownerInstance &&
            this.$ownerInstance.callMethod('acceptDataFromRenderjs', res.data);
        };
        this.source.onopen = function (event) {
          console.log('open:' + JSON.stringify(event));
        };
        this.source.onerror = function (event) {
          console.log('error:' + JSON.stringify(event) + JSON.stringify(es));
        };
      }
    },
  },
};
